package org.idea.qiyu.framework.export.pdf.utils;

import com.itextpdf.text.pdf.BaseFont;
import lombok.extern.slf4j.Slf4j;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

@Slf4j
public final class HtmlUtil {

    private HtmlUtil() {
    }

    // 字体路径，放在资源目录下
    private static final String FONT_PATH = "classpath:simsun.ttc";

    public static void file2Pdf(File htmlFile, String pdfFile) throws Exception {
        try (OutputStream os = new FileOutputStream(pdfFile)) {
            String url = htmlFile.toURI().toURL().toString();
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(url);
            // 解决中文支持
            ITextFontResolver fontResolver = renderer.getFontResolver();
            // 获取字体绝对路径，ApplicationContextUtil是我自己写的类
            String fontPath = FONT_PATH;
            fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            renderer.layout();
            renderer.createPDF(os);
        } catch (Exception e) {
            // 抛出自定义异常
            e.printStackTrace();
        }
    }

    public static void html2Pdf(String html, String pdfFile) throws Exception {
        String pdfDir = pdfFile+"/";
        File file = new File(pdfDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        try (OutputStream os = new FileOutputStream(pdfFile)) {
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(html);
            // 解决中文支持
            ITextFontResolver fontResolver = renderer.getFontResolver();
            // 获取字体绝对路径，ApplicationContextUtil是我自己写的类
            String fontPath = FONT_PATH;
            fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            renderer.layout();
            renderer.createPDF(os);
        } catch (Exception e) {
            // 抛出自定义异常
            e.printStackTrace();
        }
    }
}